import { DEFAULT_PROTABLE_OPTIONS } from '@/constants';
import {
  DownloadOutlined,
  LineChartOutlined,
  SearchOutlined,
} from '@ant-design/icons';
import { ActionType, PageContainer, ProColumns, ProTable, StatisticCard } from '@ant-design/pro-components';
import { useRequest } from '@umijs/max';
import { Button, Card, Col, DatePicker, Row, Space, Tag, Tooltip, Select, Empty } from 'antd';
import { useMemo, useRef, useState, useEffect } from 'react';
import dayjs from 'dayjs';

import { 
  getOperationLogListPaginated, 
  getOperationTypeDistribution, 
  getModuleDistribution
} from '@/services/operationLogApi';
import { Pie } from '@ant-design/charts';
import { useEnumStore } from './store/enumStore';

const { RangePicker } = DatePicker;
const { Statistic } = StatisticCard;
const { Option } = Select;

/**
 * 操作日志管理
 */
export default function OperationLogPage() {
  const [dateRange, setDateRange] = useState<[dayjs.Dayjs, dayjs.Dayjs] | null>(null);
  const tableActionRef = useRef<ActionType>();
  
  // 使用枚举值仓库
  const { 
    userRoles, modules, operationTypes, requestMethods,
    setUserRoles, setModules, setOperationTypes, setRequestMethods,
    updateFromLogs, toValueEnum
  } = useEnumStore();
  
  // 转换为ProTable需要的valueEnum格式
  const userRoleEnum = useMemo(() => toValueEnum(userRoles), [userRoles, toValueEnum]);
  const moduleEnum = useMemo(() => toValueEnum(modules), [modules, toValueEnum]);
  const operationTypeEnum = useMemo(() => toValueEnum(operationTypes), [operationTypes, toValueEnum]);
  const requestMethodEnum = useMemo(() => toValueEnum(requestMethods), [requestMethods, toValueEnum]);
  
  // 注意：不再单独发送请求获取枚举值，而是从操作日志分页查询接口的响应数据中提取
  // 初始加载时可以触发一次表格数据加载
  useEffect(() => {
    // 组件挂载时触发表格数据加载，以获取初始枚举值
    if (tableActionRef.current) {
      tableActionRef.current.reload();
    }
  }, []);

  // 获取操作类型分布数据
  const { data: operationTypeData, loading: operationTypeLoading } = useRequest(() => {
    const startTime = dateRange?.[0]?.format('YYYY-MM-DDTHH:mm:ss');
    const endTime = dateRange?.[1]?.format('YYYY-MM-DDTHH:mm:ss');
    return getOperationTypeDistribution(startTime, endTime);
  }, {
    refreshDeps: [dateRange],
  });

  // 获取模块访问分布数据
  const { data: moduleDistributionData, loading: moduleDistributionLoading } = useRequest(() => {
    const startTime = dateRange?.[0]?.format('YYYY-MM-DDTHH:mm:ss');
    const endTime = dateRange?.[1]?.format('YYYY-MM-DDTHH:mm:ss');
    return getModuleDistribution(startTime, endTime);
  }, {
    refreshDeps: [dateRange],
  });

  // 计算操作成功率
  const successRate = useMemo(() => {
    if (!operationTypeData?.data) return 0;
    
    const totalCount = operationTypeData.data.reduce((sum, item) => sum + item.count, 0);
    if (totalCount === 0) return 0;
    
    // 假设"成功"操作类型包含"成功"字样
    const successCount = operationTypeData.data
      .filter(item => item.operation.includes('成功'))
      .reduce((sum, item) => sum + item.count, 0);
    
    return Math.round((successCount / totalCount) * 100);
  }, [operationTypeData]);

  // 日期范围变化处理
  const handleDateRangeChange = (dates: any) => {
    setDateRange(dates);
    // 刷新表格
    tableActionRef.current?.reload();
  };

  // 表格列定义
  const columns = useMemo<ProColumns<OPERATION_LOG.OperationLogModel>[]>(
    () => [
      {
        dataIndex: 'index',
        valueType: 'indexBorder',
        width: 48,
        title: '序号',
      },
      {
        dataIndex: 'username',
        title: '用户名',
        width: 100,
      },
      {
        dataIndex: 'userRole',
        title: '用户角色',
        width: 100,
        valueEnum: userRoleEnum,
        // 如果后端API未就绪，可以使用request属性动态加载
        // request: async () => {
        //   const res = await getUserRoleEnum();
        //   return res.data?.map(item => ({
        //     label: item.label,
        //     value: item.value,
        //   })) || [];
        // },
      },
      {
        dataIndex: 'module',
        title: '操作模块',
        width: 100,
        valueEnum: moduleEnum,
        // 如果后端API未就绪，可以使用request属性动态加载
        // request: async () => {
        //   const res = await getModuleEnum();
        //   return res.data?.map(item => ({
        //     label: item.label,
        //     value: item.value,
        //   })) || [];
        // },
      },
      {
        dataIndex: 'operation',
        title: '操作类型',
        width: 100,
        valueEnum: operationTypeEnum,
        // 如果后端API未就绪，可以使用request属性动态加载
        // request: async () => {
        //   const res = await getOperationTypeEnum();
        //   return res.data?.map(item => ({
        //     label: item.label,
        //     value: item.value,
        //   })) || [];
        // },
      },
      {
        dataIndex: 'description',
        title: '操作描述',
        width: 180,
        ellipsis: true,
      },
      {
        dataIndex: 'method',
        title: '请求方法',
        width: 80,
        valueEnum: requestMethodEnum,
        // 如果后端API未就绪，可以使用request属性动态加载
        // request: async () => {
        //   const res = await getRequestMethodEnum();
        //   return res.data?.map(item => ({
        //     label: item.label,
        //     value: item.value,
        //   })) || [];
        // },
        render: (_, record) => {
          let color = 'default';
          if (record.method === 'GET') color = 'blue';
          if (record.method === 'POST') color = 'green';
          if (record.method === 'PUT') color = 'orange';
          if (record.method === 'DELETE') color = 'red';
          return <Tag color={color}>{record.method}</Tag>;
        },
      },
      {
        dataIndex: 'requestUrl',
        title: '请求URL',
        width: 150,
        ellipsis: true,
      },
      {
        dataIndex: 'requestParams',
        title: '请求参数',
        width: 150,
        ellipsis: true,
        render: (_, record) => {
          if (!record.requestParams) return '-';
          
          try {
            // 尝试解析JSON
            const params = JSON.parse(record.requestParams);
            return (
              <Tooltip
                title={
                  <pre style={{ maxHeight: '300px', overflow: 'auto' }}>
                    {JSON.stringify(params, null, 2)}
                  </pre>
                }
                overlayStyle={{ maxWidth: '800px' }}
              >
                <a>查看详情</a>
              </Tooltip>
            );
          } catch (e) {
            // 如果不是JSON格式，直接显示内容
            return (
              <Tooltip title={record.requestParams}>
                <span>{record.requestParams}</span>
              </Tooltip>
            );
          }
        },
      },
      {
        dataIndex: 'requestIp',
        title: '请求IP',
        width: 120,
      },
      {
        dataIndex: 'status',
        title: '操作状态',
        width: 100,
        valueEnum: {
          true: { text: '成功', status: 'Success' },
          false: { text: '失败', status: 'Error' },
        },
        render: (_, record) => {
          const status = record.status ? 'success' : 'error';
          const text = record.status ? '成功' : '失败';
          return <Tag color={status}>{text}</Tag>;
        },
      },
      {
        dataIndex: 'errorMsg',
        title: '错误消息',
        width: 150,
        hideInSearch: true,
        ellipsis: true,
        render: (_, record) => {
          return record.errorMsg || '-';
        },
      },
      {
        dataIndex: 'operateTime',
        title: '操作时间',
        width: 180,
        hideInSearch: true,
        render: (_, record) => {
          return record.operateTime ? dayjs(record.operateTime).format('YYYY-MM-DD HH:mm:ss') : '-';
        },
      },
      {
        dataIndex: 'duration',
        title: '执行时长(ms)',
        width: 100,
        hideInSearch: true,
        render: (_, record) => {
          // 根据执行时长设置不同的颜色
          let color = 'success';
          if (record.duration > 1000) color = 'warning';
          if (record.duration > 3000) color = 'error';
          return <Tag color={color}>{record.duration}</Tag>;
        },
      },
      {
        dataIndex: 'operateTime',
        title: '操作时间',
        hideInTable: true,
        valueType: 'dateRange',
        search: {
          transform: (value: any) => {
            return {
              startTime: value[0] ? dayjs(value[0]).format('YYYY-MM-DDTHH:mm:ss') : undefined,
              endTime: value[1] ? dayjs(value[1]).format('YYYY-MM-DDTHH:mm:ss') : undefined,
            };
          },
        },
      },
    ],
    [],
  );

  return (
    <PageContainer>
      {/* 统计卡片和日期选择器 */}
      <Card
        title="操作日志分析"
        extra={
          <Space>
            <RangePicker
              onChange={handleDateRangeChange}
              allowClear
              placeholder={['开始日期', '结束日期']}
            />
            <Tooltip title="刷新数据">
              <Button
                icon={<SearchOutlined />}
                onClick={() => {
                  // 刷新表格和统计数据
                  tableActionRef.current?.reload();
                }}
              />
            </Tooltip>
          </Space>
        }
        style={{ marginBottom: 24 }}
      >
        <Row gutter={24}>
          <Col span={12}>
            <Card title="操作类型分布" bordered={false}>
              <div style={{ height: 300 }}>
                {operationTypeData?.data?.length ? (
                  <Pie
                    loading={operationTypeLoading}
                    data={operationTypeData?.data || []}
                    angleField="count"
                    colorField="operation"
                    radius={0.8}
                    label={{
                      type: 'outer',
                      content: '{name} {percentage}',
                    }}
                    interactions={[{ type: 'pie-legend-active' }, { type: 'element-active' }]}
                  />
                ) : (
                  <Empty description="暂无数据" />
                )}
              </div>
            </Card>
          </Col>
          <Col span={12}>
            <Card title="模块访问分布" bordered={false}>
              <div style={{ height: 300 }}>
                {moduleDistributionData?.data?.length ? (
                  <Pie
                    loading={moduleDistributionLoading}
                    data={moduleDistributionData?.data || []}
                    angleField="count"
                    colorField="module"
                    radius={0.8}
                    label={{
                      type: 'outer',
                      content: '{name} {percentage}',
                    }}
                    interactions={[{ type: 'pie-legend-active' }, { type: 'element-active' }]}
                  />
                ) : (
                  <Empty description="暂无数据" />
                )}
              </div>
            </Card>
          </Col>
        </Row>
      </Card>



      {/* 操作日志表格 */}
      <ProTable<OPERATION_LOG.OperationLogModel>
        headerTitle="操作日志列表"
        actionRef={tableActionRef}
        columns={columns}
        request={async (params) => {
          // 转换参数
          const { current, pageSize, ...rest } = params;
          // 添加日期范围
          const queryParams: OPERATION_LOG.OperationLogListParams = {
            pageNum: current,
            pageSize,
            ...rest,
          };
          
          // 如果有日期范围，添加到查询参数
          if (dateRange && dateRange[0] && dateRange[1]) {
            queryParams.startTime = dateRange[0].format('YYYY-MM-DDTHH:mm:ss');
            queryParams.endTime = dateRange[1].format('YYYY-MM-DDTHH:mm:ss');
          }
          
          // 调用API
          const res = await getOperationLogListPaginated(queryParams);
          
          // 从返回的数据中提取并更新枚举值
          if (res.code === 200 && res.data.list && res.data.list.length > 0) {
            updateFromLogs(res.data.list);
          }
          
          return {
            data: res.data.list,
            success: res.code === 200,
            total: res.data.total,
          };
        }}
        {...DEFAULT_PROTABLE_OPTIONS}
        toolBarRender={() => [
          <Button
            key="export"
            type="primary"
            icon={<DownloadOutlined />}
            onClick={() => {
              // 导出功能，可以根据需要实现
              alert('导出功能待实现');
            }}
          >
            导出
          </Button>,
          <Button
            key="chart"
            icon={<LineChartOutlined />}
            onClick={() => {
              // 可以实现跳转到更详细的图表分析页面
              alert('图表分析功能待实现');
            }}
          >
            图表分析
          </Button>,
        ]}
      />
    </PageContainer>
  );
}